// 封装购物车模块
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { insertCartAPI, deleteCartAPI, getNewCartListAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore();
  const isLogin = computed(() => userStore.userInfo.token);

  const cartList = ref([]);
  const totalCount = computed(() => cartList.value.reduce((acc, curr) => acc + curr.count, 0));
  const totalPrice = computed(() => cartList.value.reduce((acc, curr) => acc + curr.count * curr.price, 0));
  const isAllCheck = computed(() => cartList.value.every(item => item.selected));
  const selectedCount = computed(() => cartList.value
    .filter(item => item.selected)
    .reduce((acc, curr) => acc + curr.count, 0)
  );
  const selectedPrice = computed(() => cartList.value
    .filter(item => item.selected)
    .reduce((acc, curr) => acc + curr.count * curr.price, 0)
  );
  const updateCartList = async () => cartList.value = (await getNewCartListAPI()).result;
  const addCart = async goods => {
    if (isLogin.value) {
      if (!goods.count) {
        goods.count = 1;
      }
      await insertCartAPI(goods);
      await updateCartList();
    } else {
      const item = cartList.value.find(item => item.skuId === goods.skuId);
      if (item) {
        item.count++;
      } else {
        goods.count = 1;
        cartList.value.push(goods);
      }
    }
  };
  const delCart = async skuId => {
    if (isLogin.value) {
      await deleteCartAPI([skuId]);
      await updateCartList();
    } else {
      const idx = cartList.value.findIndex(item => item.skuId === skuId);
      cartList.value.splice(idx, 1);
    }
  };
  const clearCart = () => cartList.value = [];
  const singleCheck = (skuId, selected) => cartList.value.find(item => item.skuId === skuId).selected = selected;
  const allCheck = (selected) => cartList.value.forEach(item => item.selected = selected);
  return {
    cartList,
    totalCount,
    totalPrice,
    isAllCheck,
    selectedCount,
    selectedPrice,
    updateCartList,
    addCart,
    delCart,
    clearCart,
    singleCheck,
    allCheck
  };
}, { persist: true });